import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:steam_app/config/app_routes.dart';

import '../../config/app_theme.dart';
import '../../entity/game.dart';
import '../../entity/user.dart';
import '../../provider/home_provider.dart';
import '../../provider/user_provider.dart';
import '../null_page/news_page.dart';
import '../null_page/notification_page.dart';
import '../security/token_page.dart';
import '../widgets/game_promo_card.dart';
import '../widgets/user_avatar.dart';
import '../wishlist/wishlist_page.dart';
import '../menu_info/menu_info_page.dart';


class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _currentIndex = 0;
  bool _isWishlistView = false;


  @override
  Widget build(BuildContext context) {
    final user = context.watch<UserProvider>().currentUser;

    if (user == null) {
      print('currentUser 为 null，_currentIndex = $_currentIndex');
      //当用户数据为空时，展示加载状态
      return Scaffold(
        body: Center(child: CircularProgressIndicator()),
      );
    }

    final List<Widget> _pages = [
      HomeContentWithTopBar(
        user: user,
        onWishlistPressed: () => setState(() => _isWishlistView = true),
        onResetPressed: () => setState(() => _isWishlistView = false),
        onPageChange: (index) {
          setState(() {
            _isWishlistView = false;
            _currentIndex = index;
          });
        },
      ), //主页内容
      const NewsPage(), //资讯页面
      const TokenPage(), //令牌页面
      const NotificationPage(), //消息页面
      MenuInfoPage(
        onNavigate: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
      ), //菜单信息页
    ];

    return Scaffold(
      //顶部固定块
      appBar: AppBar(
        //左侧留空或放置菜单按钮
        leading: const Icon(Icons.more_vert),
        title: _buildSearchBox(),
        actions: [
          //用户头像区域
          Padding(
          padding: const EdgeInsets.only(right: 16.0),
          child: UserAvatar(
            user: user,
            onTap: () {
              Navigator.of(context).pushNamed(user_page);
              }
          ),
          ),
        ],
      ),

      //页面内容
      body: _isWishlistView
          ? WishlistPage(onBack: () => setState(() => _isWishlistView = false))
          : _pages[_currentIndex],

      //底部固定块
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },

        type: BottomNavigationBarType.fixed,
        //选中项颜色
        selectedItemColor: themeTagColor,
        items: const [
          BottomNavigationBarItem(icon: Icon(Icons.local_offer), label: '商店'),
          BottomNavigationBarItem(icon: Icon(Icons.article ), label: '资讯'),
          BottomNavigationBarItem(icon: Icon(Icons.shield), label: '安全'),
          BottomNavigationBarItem(icon: Icon(Icons.notifications), label: '消息'),
          BottomNavigationBarItem(icon: Icon(Icons.menu), label: '选项'),
        ],
      ),
    );
  }

  //搜索框
  Widget _buildSearchBox() {
    return Container(
      height: searchBoxSize,
      decoration: BoxDecoration(
        color: searchBox,
        borderRadius: BorderRadius.circular(borderRadiusSize),
      ),
      child: const TextField(
        style: TextStyle(color: textColor),
        decoration: InputDecoration(
          hintText: 'STEAM',
          hintStyle: TextStyle(color: dimTextColor),
          prefixIcon: Icon(Icons.search, color: dimTextColor),
          border: InputBorder.none,
        ),
      ),
    );
  }
}

class HomeContentWithTopBar extends StatelessWidget {
  final User user;
  final VoidCallback onWishlistPressed;
  final VoidCallback onResetPressed;
  final Function(int) onPageChange; //用于页面切换的回调函数

  const HomeContentWithTopBar({
    super.key,
    required this.user,
    required this.onWishlistPressed,
    required this.onResetPressed,
    required this.onPageChange,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        _buildTopActions(context, onPageChange),
        const Divider(height: 1),
        Expanded(child: HomeContentView(user: user)),
      ],
    );
  }

  Widget _buildTopActions(BuildContext context, Function(int) onPageChange) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: hPaddingSize, vertical: vPaddingSize),
      color: Theme.of(context).appBarTheme.backgroundColor,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          PopupMenuButton<String>(
            onSelected: (value) {
              if (value == 'news') {
                onPageChange(1);
              }
              else if (value == 'store') {
                onResetPressed(); //切回商店视图
              }
            },
            itemBuilder: (BuildContext context) => const [
              PopupMenuItem<String>(value: 'news', child: Text('新闻')),
              PopupMenuItem<String>(value: 'store', child: Text('商店')),
              PopupMenuItem<String>(value: 'community', child: Text('社区')),
            ],
            child: const Row(
              children: [
                SizedBox(width: 10),
                Text('菜单'),
              ],
            ),
          ),
          TextButton(
            onPressed: onWishlistPressed,
            child: const Text('愿望单'),
          ),
          TextButton(
            onPressed: () {},
            child: Text('钱包 (¥${user.balance.toStringAsFixed(2)})'),
          ),
        ],
      ),
    );
  }
}


class HomeContentView extends StatelessWidget {
  final User user;

  const HomeContentView({super.key, required this.user});

  @override
  Widget build(BuildContext context) {
    //将Consumer移到顶层，以便两个列表都能使用provider的数据
    return Consumer<HomeProvider>(
      builder: (context, provider, child) {
        if (provider.isLoading) {
          return const Center(child: CircularProgressIndicator());
        }
        if (provider.errorMessage != null) {
          return Center(child: Text(provider.errorMessage!));
        }
        if (provider.games.isEmpty) {
          return const Center(child: Text('没有可显示的游戏。'));
        }

        //使用ListView组合所有垂直排列的组件
        return ListView(
          children: [
            const Padding(
              padding: EdgeInsets.all(hPaddingSize),
              child: Text(
                '今日特惠',
                style: TextStyle(fontSize: titleFontSize, fontWeight: titleFontWeight),
              ),
            ),
            //横向轮播列表
            _buildCarouselSlider(provider.games),

            const Padding(
              padding: EdgeInsets.all(hPaddingSize),
              child: Text(
                '精选与推荐',
                style: TextStyle(fontSize: titleFontSize, fontWeight: titleFontWeight),
              ),
            ),
            //垂直游戏卡片列表
            _buildGameList(provider.games),
          ],
        );
      },
    );
  }

  //构建轮播图
  Widget _buildCarouselSlider(List<Game> games) {
    return CarouselSlider.builder(
      itemCount: games.length,
      itemBuilder: (context, index, realIndex) {
        final game = games[index];
        return Container(
          margin: const EdgeInsets.symmetric(horizontal: 5.0),
          child: ClipRRect(
            borderRadius: const BorderRadius.all(Radius.circular(8.0)),
            child: Image.asset(game.coverImage, fit: BoxFit.cover, width: 1000),
          ),
        );
      },
      options: CarouselOptions(
        autoPlay: true, //自动播放
        enlargeCenterPage: true, //当前页放大
        aspectRatio: 16 / 9, //宽高比
        viewportFraction: 0.8, //每个页面占屏幕的比例
      ),
    );
  }

  //构建垂直游戏列表的方法，接收游戏列表作为参数
  Widget _buildGameList(List<Game> games) {
    return Column(
      children: games.map((game) => GamePromoCard(game: game)).toList(),
    );
  }
}